package org.zhangyp.pdf;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.zhangyp.MysqlUtil;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 简单的Word文档读取工具类
 * 用于读取.docx格式的Word文档并输出其内容
 */
public class WordReaderUtil {

    /**
     * 读取Word文档并返回其文本内容
     * @param filePath Word文档路径
     * @return 文档的文本内容
     * @throws IOException 如果读取文件时发生错误
     */
    public static String readWordDocument(String filePath) throws IOException {
        StringBuilder content = new StringBuilder();

        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            // 获取文档中的所有段落
            List<XWPFParagraph> paragraphs = document.getParagraphs();

            // 遍历每个段落并提取文本
            for (XWPFParagraph paragraph : paragraphs) {
                content.append(paragraph.getText());
                content.append("\n"); // 段落之间添加换行符
            }
        }

        return content.toString();
    }

    /**
     * 读取Word文档并将内容打印到控制台
     * @param filePath Word文档路径
     */
    public static void printWordContent(String filePath) {
        MysqlUtil util = new MysqlUtil("root", "ZxZl@610016", "14.103.177.16", "drg_group", "3306");
        List<HashMap<String, Object>> adrgMapList = util.PreparedStatement("select * from dict_cq_drgs");
        List<String> drgCodeList = adrgMapList.stream().map(mdc -> mdc.get("drg_code").toString()).toList();
        System.out.println("缓存drg数据条数：" + drgCodeList.size());


        try {
            String content = readWordDocument(filePath);
            System.out.println("Word文档内容:");
            System.out.println("------------------------------");
            // 按换行符分割文本为行
            String[] lines = content.split("\\r?\\n");
            for (String line : lines) {
                System.out.println(line);
            }

            // 使用自定义的分割方法，只分割前两个空格
            int count = 0;
            String drgCode = "";
            List<List<String>> dataValuesList = new ArrayList<>();
            List<List<String>> factorValuesList = new ArrayList<>();

            for (int i = 0; i < lines.length; i++) {
                String line = lines[i].trim();
                try {
                    Integer.parseInt(line);
                } catch (NumberFormatException e) {
                    // 不是数字，继续处理
                    count++;
                    // 使用自定义方法分割前两个空格
                    String[] parts = splitFirstOneSpaces(line);
                    boolean factorFlag = true;
                    if (parts.length == 2) {
                        String value1 = parts[0];
                        if (drgCodeList.contains(value1)) {
                            drgCode = value1;
                            factorFlag = false;
                        }else if (value1.contains(".")) {
                            factorFlag = false;
                            String value2;
                            value2 = parts[1];
                            if (value1.contains("'")) {
                                value1 = value1.replace("'", "\\'");
                            }
                            if (value2.contains("'")) {
                                value2 = value2.replace("'", "\\'");
                            }
                            List<String> dataValues = new ArrayList<>();
                            dataValues.add("'" + value1 + "'");
                            dataValues.add("'" + value2 + "'");
                            dataValues.add("'" + drgCode + "'");
                            dataValues.add("" + count);
                            dataValuesList.add(dataValues);

                            if (dataValuesList.size() == 1000) {
                                insertAdrgData(dataValuesList, util);
                                dataValuesList.clear();
                            }
                        } else {
                            System.out.println(parts[0] + "   " + parts[1]);
                        }
                    }
                    if (factorFlag) {
                        List<String> factorValues = new ArrayList<>();
                        if (line.contains("'")) {
                            line = line.replace("'", "\\'");
                        }
                        factorValues.add("'" + line + "'");
                        factorValues.add(drgCode.isEmpty()?"NULL":"'" + drgCode + "'");
                        factorValues.add("" + count);
                        factorValuesList.add(factorValues);

                        if (factorValuesList.size() == 1000) {
                            insertFactorData(factorValuesList, util);
                            factorValuesList.clear();
                        }
                    }
                }

            }
            if (!dataValuesList.isEmpty()) {
                insertAdrgData(dataValuesList, util);
            }

            if (!factorValuesList.isEmpty()) {
                insertFactorData(factorValuesList, util);
            }
            System.out.println("提取有效数据行数：" + count);
            //关流
            util.close();
            System.out.println("------------------------------");
        } catch (IOException e) {
            System.err.println("读取Word文档时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 主方法，用于测试Word文档读取功能
     * 注意：运行此方法前，请确保提供的文件路径存在
     */
    public static void main(String[] args) {
        // 示例用法 - 请替换为实际的Word文档路径
        String filePath = "C:\\Users\\10160\\my\\drg\\11111.docx";
        printWordContent(filePath);
    }


    private static void insertAdrgData(List<List<String>> valuesList, MysqlUtil util) {
        List<String> valuesSql = new ArrayList<>();
        for (List<String> row : valuesList) {
            valuesSql.add("(" + String.join(",", row) + ")");
        }
        String sql = "INSERT INTO cq_drg_data_temp (data_code, data_name, drg_code, seq) VALUES " + String.join(",", valuesSql) + ";";
        util.Insert(sql);
    }

    private static void insertFactorData(List<List<String>> valuesList, MysqlUtil util) {
        List<String> valuesSql = new ArrayList<>();
        for (List<String> row : valuesList) {
            valuesSql.add("(" + String.join(",", row) + ")");
        }
        String sql = "INSERT INTO cq_factor_temp (factor_desc, drg_code, seq) VALUES " + String.join(",", valuesSql) + ";";
        util.Insert(sql);
    }

    /**
     * 自定义方法：只分割字符串中的前一个空格
     *
     * @param input 输入字符串
     * @return 分割后的字符串数组，最多包含3个元素
     */
    public static String[] splitFirstOneSpaces(String input) {
        /*if (input.contains("手术或操作")) {
            // 一些特殊关键字，不分割
            return new String[]{input};
        }*/

        // 查找第一个空格的位置
        int firstSpacePos = input.indexOf(" ");

        if (firstSpacePos == -1) {
            firstSpacePos = input.indexOf("\t");
            if (firstSpacePos == -1) {
                // 没有空格，返回原字符串
                return new String[]{input};
            }
        }
        // 分割成两部分
        return new String[]{
                input.substring(0, firstSpacePos).trim(),
                input.substring(firstSpacePos + 1).trim()
        };
    }
}
